﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.UI.WebControls;
using Hematology.Data;
using Hematology.Tools;
using Hematology.Tools.Text;
using Hematology.UserSite.Controls;

namespace Hematology.UserSite.admin
{
	public partial class LetterTemplates : NgoPage
	{
		#region Fields

		private const string ListUrl = "/admin/LetterTemplates.aspx?view=List";

		#endregion

		#region Properties

		private EnumHelper.PageSection CurrentPageSection
		{
			get
			{
				return ViewState["CurrentPageSection"] != null
						   ? (EnumHelper.PageSection)Enum.Parse(typeof(EnumHelper.PageSection), ViewState["CurrentPageSection"].ToString())
						   : EnumHelper.PageSection.List;
			}
			set { ViewState["CurrentPageSection"] = value; }
		}

		private EmailTemplate CurrentEmailTemplate
		{
			get { return (EmailTemplate)ViewState["CurrentEmailTemplate"]; }
			set { ViewState["CurrentEmailTemplate"] = value; }
		}

		#endregion

		#region Fill methods

		private void FillViewStateVariables()
		{
			string pageSection = Request.QueryString["view"];
			if (Array.IndexOf(Enum.GetNames(typeof(EnumHelper.PageSection)), pageSection) > -1)
			{
				CurrentPageSection =
					(EnumHelper.PageSection)Enum.Parse(typeof(EnumHelper.PageSection), pageSection);
			}
		}

		private void FillEmailTemplateList()
		{
			List<EmailTemplate> lEmailTemplate = EmailTemplate.GetAllEmailTemplates();

			rptEmailTemplates.DataSource = lEmailTemplate;
			rptEmailTemplates.DataBind();

			ptTitle.ShowButton = lEmailTemplate.Count < Enum.GetNames(typeof(EnumHelper.EmailTemplateType)).Length;
		}

		private void FillFileAttachList(int templateId)
		{
			btnSaveAttach.Visible = true;

			List<FileAttach> lEmailAttach = FileAttach.ListByTemplateId(templateId);
			if (lEmailAttach != null && lEmailAttach.Count != 0)
			{
				rptEmailAttach.DataSource = lEmailAttach;
				rptEmailAttach.DataBind();
			}
		}

		private void FillEmailTemplateTypeList()
		{
			SortedList<string, int> slEmailTemplateTypes = new SortedList<string, int>();

			int[] enumValues = (int[])Enum.GetValues(typeof(EnumHelper.EmailTemplateType));
			string[] enumNames = Enum.GetNames(typeof(EnumHelper.EmailTemplateType));

			List<EmailTemplate> lEmailTemplate = EmailTemplate.GetAllEmailTemplates();

			for (int i = 0; i < enumValues.Length; i++)
			{
				if (lEmailTemplate.Where(et => et.TemplateType == enumValues[i]).FirstOrDefault() == null)
				{
					slEmailTemplateTypes.Add(enumNames[i], enumValues[i]);
				}
			}

			if (slEmailTemplateTypes.Count != 0)
			{
				pnlTemplateType.Visible = true;

				ddlTemplateType.DataTextField = "Key";
				ddlTemplateType.DataValueField = "Value";

				ddlTemplateType.DataSource = slEmailTemplateTypes;
				ddlTemplateType.DataBind();
			}
		}

		private void FillEditForm()
		{
			string sEmailTemplateId = Request.QueryString["id"];
			int iEmailTemplateId;
			if (!String.IsNullOrEmpty(sEmailTemplateId) && int.TryParse(sEmailTemplateId, out iEmailTemplateId))
			{
				EmailTemplate emailTemplate = EmailTemplate.Get(iEmailTemplateId);
				if (emailTemplate != null)
				{
					CurrentEmailTemplate = emailTemplate;
					FillFileAttachList(iEmailTemplateId);

					txtUserMailSubject.Text = emailTemplate.Subject;
					ckedUserMailContent.Text = emailTemplate.Content;
				}
			}
		}

		private void FillPage()
		{
			switch (CurrentPageSection)
			{
				case EnumHelper.PageSection.Edit:
				case EnumHelper.PageSection.Add:
					ToolbarSetup();
					FillEmailTemplateTypeList();
					FillEditForm();

					mvLetterTemplates.ActiveViewIndex = 1;

					break;
				default:
					FillEmailTemplateList();

					mvLetterTemplates.ActiveViewIndex = 0;

					break;
			}
		}

		#endregion

		#region Other methods
		
		private void ToolbarSetup()
		{
			ckedUserMailContent.config.skin = "office2003";
			ckedUserMailContent.config.toolbar = PageHelper.EditorButtonSet;

			ckedUserMailContent.DisableObjectResizing = true;
			ckedUserMailContent.ResizeEnabled = false;
			ckedUserMailContent.Width = 904;
		}

		private void SaveAttach(int iTemplateId)
		{
			if (String.IsNullOrEmpty(fuAttachFile.FileName))
				return;
			
			if (!fuAttachFile.HasFile || !FileValidate(fuAttachFile.PostedFile.ContentType))
				return;

			string sFullPath = Path.Combine(Server.MapPath(ConfigReader.EmailTemplateAttachmentsPath), fuAttachFile.FileName);
			
			FileStream fsWriteAttachmentStream = new FileStream(sFullPath, FileMode.Create, FileAccess.ReadWrite);
			using (BinaryWriter binWriter = new BinaryWriter(fsWriteAttachmentStream))
			{
				binWriter.Write(FileHelper.ReadFileContent(fuAttachFile.PostedFile.InputStream));
				binWriter.Close();
			}

			if (!File.Exists(sFullPath))
				return;

			FileAttach emailTemplateAttach = new FileAttach
			{
				TemplateId = iTemplateId,
				DocumentName = fuAttachFile.FileName,
				DocumentType = fuAttachFile.PostedFile.ContentType,
				DocumentSize = fuAttachFile.PostedFile.ContentLength
			};

			emailTemplateAttach.Save();
			if (!emailTemplateAttach.AttachId.HasValue)
				return;
				
			FillFileAttachList(iTemplateId);
		}

		protected bool FileValidate(string sContentType)
		{
			string[] sGrantedTypes = TextHelper.AllowedFileTypes;
			return Array.IndexOf(sGrantedTypes, sContentType) != -1;
		}

		#endregion

		#region Event handlers

		protected void Page_Load(object sender, EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				FillViewStateVariables();
				FillPage();
			}
		}

		protected void btnSaveTempalte_Click(object sender, EventArgs e)
		{
			if (CurrentPageSection == EnumHelper.PageSection.Add)
			{
				EmailTemplate emailTemplate = new EmailTemplate
												  {
													  Content = ckedUserMailContent.Text,
													  Subject = txtUserMailSubject.Text,
													  TemplateType = Convert.ToInt32(ddlTemplateType.SelectedValue)
												  };

				emailTemplate.Save();

				if (emailTemplate.TemplateId.HasValue)
				{
					SaveAttach(emailTemplate.TemplateId.Value);
					Response.Redirect(ListUrl);
				}
			}

			if (CurrentPageSection == EnumHelper.PageSection.Edit)
			{
				CurrentEmailTemplate.Content = ckedUserMailContent.Text;
				CurrentEmailTemplate.Subject = txtUserMailSubject.Text.Trim();

				CurrentEmailTemplate.UpdateInstance();

				Response.Redirect(ListUrl);
			}
		}

		protected void rptEmailTemplates_ItemCommand(object source, RepeaterCommandEventArgs e)
		{
			if (e.CommandName == "EditTemplate")
			{
				Response.Redirect("/admin/LetterTemplates.aspx?view=Edit");
			}
		}

		protected void btnSaveAttach_Click(object sender, EventArgs e)
		{
			if (CurrentEmailTemplate != null && CurrentEmailTemplate.TemplateId.HasValue)
			{
				SaveAttach(CurrentEmailTemplate.TemplateId.Value);
			}
		}

		protected void rptEmailAttach_ItemCommand(object source, RepeaterCommandEventArgs e)
		{
			if (e.CommandName == "DeleteAttach")
			{
				int iAttachId = Convert.ToInt32(e.CommandArgument);
				FileAttach emailTemplateAttach = FileAttach.Get(iAttachId);
				emailTemplateAttach.IsDeleted = true;

				emailTemplateAttach.UpdateInstance();

				if (CurrentEmailTemplate.TemplateId != null)
				{
					FillFileAttachList(CurrentEmailTemplate.TemplateId.Value);
				}
			}
			else if (e.CommandName == "OpenAttach")
			{
				int iAttachId = Convert.ToInt32(e.CommandArgument);
				FileAttach fileAttach = FileAttach.Get(iAttachId);
				if (fileAttach != null)
				{
					Response.Redirect(Path.Combine(ConfigReader.EmailTemplateAttachmentsPath, fileAttach.DocumentName));
				}
			}
		}

		protected void btnList_Click(object sender, EventArgs e)
		{
			Response.Redirect(ListUrl);
		}

		#endregion
	}
}